// JSON工具专用功能
class JSONTool {
    constructor() {
        this.init();
    }

    init() {
        this.bindEvents();
    }

    bindEvents() {
        // 输入方式切换标签
        const inputTabs = document.querySelectorAll('#json-tool .input-tab');
        inputTabs.forEach(tab => {
            tab.addEventListener('click', (e) => {
                e.preventDefault();
                const tabName = e.target.dataset.tab;
                this.switchInputTab(tabName);
            });
        });

        // 实时验证输入
        const jsonInputs = document.querySelectorAll('textarea[id^="json-input-"]');
        jsonInputs.forEach(input => {
            input.addEventListener('input', () => {
                this.validateJSONInput(input);
            });
        });
        
        // 确保标签页切换功能正常工作
        this.ensureTabSwitching();
    }
    
    // 确保标签页切换功能正常工作
    ensureTabSwitching() {
        // 为所有标签页按钮添加点击事件
        const tabs = document.querySelectorAll('#json-tool .input-tab');
        tabs.forEach(tab => {
            tab.addEventListener('click', (e) => {
                e.preventDefault();
                const tabName = e.target.getAttribute('data-tab');
                if (tabName) {
                    this.switchInputTab(tabName);
                }
            });
        });
    }

    switchInputTab(tabName) {
        console.log('切换到标签页:', tabName); // 添加调试日志
        
        // 更新标签状态
        document.querySelectorAll('#json-tool .input-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        const targetTab = document.querySelector(`#json-tool [data-tab="${tabName}"]`);
        if (targetTab) {
            targetTab.classList.add('active');
        }

        // 更新内容区域
        document.querySelectorAll('#json-tool .input-content').forEach(content => {
            content.classList.remove('active');
        });
        const targetContent = document.getElementById(`${tabName}-input`);
        if (targetContent) {
            targetContent.classList.add('active');
        }
        
        console.log('标签页切换完成'); // 添加调试日志
    }

    // 验证JSON输入
    validateJSONInput(textarea) {
        const value = textarea.value.trim();
        if (!value) {
            textarea.style.borderColor = '';
            return true;
        }

        try {
            JSON.parse(value);
            textarea.style.borderColor = '#28a745'; // 绿色表示有效
            return true;
        } catch (e) {
            textarea.style.borderColor = '#dc3545'; // 红色表示无效
            return false;
        }
    }

    // 格式化JSON
    formatJSON() {
        const input = document.getElementById('json-input-format').value.trim();
        if (!input) {
            this.showToast('请输入JSON数据', 'warning');
            return;
        }

        try {
            const jsonObj = JSON.parse(input);
            const indentType = document.getElementById('indent-type').value;
            const indentSize = parseInt(document.getElementById('indent-size').value);
            
            let indent;
            if (indentType === 'tab') {
                indent = '\t';
            } else {
                indent = ' '.repeat(indentSize);
            }
            
            const formatted = JSON.stringify(jsonObj, null, indent);
            document.getElementById('json-output-format').value = formatted;
            this.showToast('JSON格式化成功', 'success');
        } catch (e) {
            this.showToast('JSON格式错误: ' + e.message, 'error');
        }
    }

    // 压缩JSON
    compressJSON() {
        const input = document.getElementById('json-input-format').value.trim();
        if (!input) {
            this.showToast('请输入JSON数据', 'warning');
            return;
        }

        try {
            const jsonObj = JSON.parse(input);
            const compressed = JSON.stringify(jsonObj);
            document.getElementById('json-output-format').value = compressed;
            this.showToast('JSON压缩成功', 'success');
        } catch (e) {
            this.showToast('JSON格式错误: ' + e.message, 'error');
        }
    }

    // Unicode转汉字
    unicodeToChinese() {
        const input = document.getElementById('json-input-format').value.trim();
        if (!input) {
            this.showToast('请输入JSON数据', 'warning');
            return;
        }

        try {
            // 先尝试解析JSON，确保格式正确
            const jsonObj = JSON.parse(input);
            
            // 将JSON对象转换为字符串，然后处理Unicode转义序列
            let jsonString = JSON.stringify(jsonObj, null, 4);
            
            // 处理标准Unicode转义序列 (\uXXXX)
            let converted = jsonString.replace(/\\u[\dA-F]{4}/gi, (match) => {
                return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
            });
            
            // 处理非标准格式 (\汉字)和(\标点)
            converted = converted.replace(/\\([\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef])/g, (match, char) => {
                return char;
            });
            
            document.getElementById('json-output-format').value = converted;
            this.showToast('Unicode转换成功', 'success');
        } catch (e) {
            // 如果JSON解析失败，尝试直接处理文本中的Unicode
            try {
                let converted = input;
                
                // 处理标准Unicode转义序列 (\uXXXX)
                converted = converted.replace(/\\u[\dA-F]{4}/gi, (match) => {
                    return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
                });
                
                // 处理非标准格式 (\汉字)和(\标点)
                converted = converted.replace(/\\([\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef])/g, (match, char) => {
                    return char;
                });
                
                document.getElementById('json-output-format').value = converted;
                this.showToast('Unicode转换成功', 'success');
            } catch (e2) {
                this.showToast('转换失败: ' + e.message, 'error');
            }
        }
    }

    // 验证JSON
    validateJSON() {
        const input = document.getElementById('json-input-validate').value.trim();
        const resultDiv = document.getElementById('validation-result');
        
        if (!input) {
            resultDiv.innerHTML = '<div class="alert alert-warning">请输入JSON数据</div>';
            return;
        }

        try {
            const jsonObj = JSON.parse(input);
            const stats = this.getJSONStats(jsonObj);
            
            resultDiv.innerHTML = `
                <div class="alert alert-success">
                    <h4>✅ JSON格式正确</h4>
                    <div class="json-stats">
                        <p><strong>数据类型:</strong> ${Array.isArray(jsonObj) ? '数组' : typeof jsonObj}</p>
                        <p><strong>键数量:</strong> ${stats.keys}</p>
                        <p><strong>值数量:</strong> ${stats.values}</p>
                        <p><strong>嵌套深度:</strong> ${stats.depth}</p>
                        <p><strong>字符数:</strong> ${input.length}</p>
                    </div>
                </div>
            `;
        } catch (e) {
            const errorInfo = this.parseJSONError(e.message, input);
            resultDiv.innerHTML = `
                <div class="alert alert-error">
                    <h4>❌ JSON格式错误</h4>
                    <p><strong>错误信息:</strong> ${e.message}</p>
                    <p><strong>错误位置:</strong> 行 ${errorInfo.line}, 列 ${errorInfo.column}</p>
                    <div class="error-context">
                        <pre>${errorInfo.context}</pre>
                    </div>
                </div>
            `;
        }
    }

    // 获取JSON统计信息
    getJSONStats(obj, depth = 0) {
        let stats = {
            keys: 0,
            values: 0,
            depth: depth
        };

        if (obj === null || typeof obj !== 'object') {
            stats.values = 1;
            return stats;
        }

        if (Array.isArray(obj)) {
            stats.values = obj.length;
            for (const item of obj) {
                if (typeof item === 'object' && item !== null) {
                    const itemStats = this.getJSONStats(item, depth + 1);
                    stats.keys += itemStats.keys;
                    stats.values += itemStats.values;
                    stats.depth = Math.max(stats.depth, itemStats.depth);
                } else {
                    stats.values++;
                }
            }
        } else {
            const keys = Object.keys(obj);
            stats.keys = keys.length;
            stats.values = keys.length;
            
            for (const key of keys) {
                if (typeof obj[key] === 'object' && obj[key] !== null) {
                    const valueStats = this.getJSONStats(obj[key], depth + 1);
                    stats.keys += valueStats.keys;
                    stats.values += valueStats.values;
                    stats.depth = Math.max(stats.depth, valueStats.depth);
                }
            }
        }

        return stats;
    }

    // 解析JSON错误信息
    parseJSONError(message, json) {
        // 尝试从错误消息中提取位置信息
        const positionMatch = message.match(/position (\d+)/);
        let position = positionMatch ? parseInt(positionMatch[1]) : 0;
        
        // 计算行和列
        const lines = json.substring(0, position).split('\n');
        const line = lines.length;
        const column = lines[lines.length - 1].length + 1;
        
        // 获取错误上下文
        const contextStart = Math.max(0, position - 50);
        const contextEnd = Math.min(json.length, position + 50);
        let context = json.substring(contextStart, contextEnd);
        
        // 标记错误位置
        const errorPos = position - contextStart;
        context = context.substring(0, errorPos) + 
                  '<span class="error-marker">⮞</span>' + 
                  context.substring(errorPos);
        
        return {
            line,
            column,
            context
        };
    }

    // 转换JSON
    convertJSON() {
        const input = document.getElementById('json-input-convert').value.trim();
        if (!input) {
            this.showToast('请输入JSON数据', 'warning');
            return;
        }

        try {
            const jsonObj = JSON.parse(input);
            const convertType = document.getElementById('convert-type').value;
            let result = '';
            
            switch (convertType) {
                case 'xml':
                    result = this.jsonToXML(jsonObj);
                    break;
                case 'csv':
                    result = this.jsonToCSV(jsonObj);
                    break;
                case 'yaml':
                    result = this.jsonToYAML(jsonObj);
                    break;
                case 'url':
                    result = this.jsonToURLParams(jsonObj);
                    break;
                case 'properties':
                    result = this.jsonToProperties(jsonObj);
                    break;
                case 'php':
                    result = this.jsonToPHP(jsonObj);
                    break;
                default:
                    result = '不支持的转换类型';
            }
            
            document.getElementById('json-output-convert').value = result;
            this.showToast('JSON转换成功', 'success');
        } catch (e) {
            this.showToast('JSON格式错误: ' + e.message, 'error');
        }
    }

    // JSON转XML
    jsonToXML(obj, rootName = 'root') {
        let xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
        
        function convert(value, tagName) {
            if (value === null || value === undefined) {
                return `<${tagName}/>\n`;
            }
            
            if (typeof value === 'object' && !Array.isArray(value)) {
                let result = `<${tagName}>\n`;
                for (const key in value) {
                    if (value.hasOwnProperty(key)) {
                        result += convert(value[key], key);
                    }
                }
                result += `</${tagName}>\n`;
                return result;
            }
            
            if (Array.isArray(value)) {
                let result = '';
                value.forEach(item => {
                    result += convert(item, tagName);
                });
                return result;
            }
            
            return `<${tagName}>${value}</${tagName}>\n`;
        }
        
        xml += convert(obj, rootName);
        return xml;
    }

    // JSON转CSV
    jsonToCSV(obj) {
        if (Array.isArray(obj)) {
            if (obj.length === 0) return '';
            
            // 获取所有键
            const keys = new Set();
            obj.forEach(item => {
                if (typeof item === 'object' && item !== null) {
                    Object.keys(item).forEach(key => keys.add(key));
                }
            });
            
            const keyArray = Array.from(keys);
            
            // 创建CSV头部
            let csv = keyArray.join(',') + '\n';
            
            // 创建CSV行
            obj.forEach(item => {
                if (typeof item === 'object' && item !== null) {
                    const row = keyArray.map(key => {
                        const value = item[key];
                        if (value === undefined || value === null) return '';
                        if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
                            return `"${value.replace(/"/g, '""')}"`;
                        }
                        return value;
                    });
                    csv += row.join(',') + '\n';
                }
            });
            
            return csv;
        } else if (typeof obj === 'object' && obj !== null) {
            // 单个对象转为CSV
            const keys = Object.keys(obj);
            let csv = keys.join(',') + '\n';
            const values = keys.map(key => {
                const value = obj[key];
                if (value === undefined || value === null) return '';
                if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
                    return `"${value.replace(/"/g, '""')}"`;
                }
                return value;
            });
            csv += values.join(',') + '\n';
            return csv;
        }
        
        return obj.toString();
    }

    // JSON转YAML
    jsonToYAML(obj, indent = 0) {
        const spaces = '  '.repeat(indent);
        
        if (obj === null) return 'null';
        if (obj === undefined) return 'undefined';
        
        if (typeof obj === 'boolean' || typeof obj === 'number') {
            return obj.toString();
        }
        
        if (typeof obj === 'string') {
            // 如果包含特殊字符，用引号包围
            if (/[:{}\[\],&*#?|<>'"`]/.test(obj)) {
                return `"${obj.replace(/"/g, '\\"')}"`;
            }
            return obj;
        }
        
        if (Array.isArray(obj)) {
            if (obj.length === 0) return '[]';
            
            let yaml = '';
            obj.forEach(item => {
                yaml += `${spaces}- ${this.jsonToYAML(item, indent + 1).trim()}\n`;
            });
            return yaml;
        }
        
        if (typeof obj === 'object') {
            const keys = Object.keys(obj);
            if (keys.length === 0) return '{}';
            
            let yaml = '';
            keys.forEach(key => {
                yaml += `${spaces}${key}: ${this.jsonToYAML(obj[key], indent + 1).trim()}\n`;
            });
            return yaml;
        }
        
        return '';
    }

    // JSON转URL参数
    jsonToURLParams(obj, prefix = '') {
        const params = [];
        
        function process(value, key) {
            if (value === null || value === undefined) return;
            
            if (typeof value === 'object') {
                if (Array.isArray(value)) {
                    value.forEach((item, index) => {
                        process(item, `${key}[${index}]`);
                    });
                } else {
                    Object.keys(value).forEach(subKey => {
                        process(value[subKey], `${key}[${subKey}]`);
                    });
                }
            } else {
                params.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
            }
        }
        
        if (prefix) {
            process(obj, prefix);
        } else {
            Object.keys(obj).forEach(key => {
                process(obj[key], key);
            });
        }
        
        return params.join('&');
    }

    // JSON转Properties
    jsonToProperties(obj, prefix = '') {
        const properties = [];
        
        function process(value, key) {
            if (value === null || value === undefined) return;
            
            if (typeof value === 'object') {
                if (Array.isArray(value)) {
                    value.forEach((item, index) => {
                        process(item, `${key}[${index}]`);
                    });
                } else {
                    Object.keys(value).forEach(subKey => {
                        process(value[subKey], prefix ? `${prefix}.${key}.${subKey}` : `${key}.${subKey}`);
                    });
                }
            } else {
                const propKey = prefix ? `${prefix}.${key}` : key;
                properties.push(`${propKey}=${value}`);
            }
        }
        
        Object.keys(obj).forEach(key => {
            process(obj[key], key);
        });
        
        return properties.join('\n');
    }

    // JSON转PHP数组
    jsonToPHP(obj, indent = 0) {
        const spaces = '    '.repeat(indent);
        
        if (obj === null) return 'null';
        if (obj === undefined) return 'null';
        
        if (typeof obj === 'boolean') {
            return obj ? 'true' : 'false';
        }
        
        if (typeof obj === 'number') {
            return obj.toString();
        }
        
        if (typeof obj === 'string') {
            // 转义PHP字符串中的特殊字符
            return `'${obj.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t')}'`;
        }
        
        if (Array.isArray(obj)) {
            if (obj.length === 0) return '[]';
            
            let php = "[\n";
            obj.forEach((item, index) => {
                php += `${spaces}    ${index} => ${this.jsonToPHP(item, indent + 1)},\n`;
            });
            php += `${spaces}]`;
            return php;
        }
        
        if (typeof obj === 'object') {
            const keys = Object.keys(obj);
            if (keys.length === 0) return '[]';
            
            let php = "[\n";
            keys.forEach(key => {
                php += `${spaces}    '${key}' => ${this.jsonToPHP(obj[key], indent + 1)},\n`;
            });
            php += `${spaces}]`;
            return php;
        }
        
        return 'null';
    }

    // 清空输入
    clearJSONInput() {
        document.getElementById('json-input-format').value = '';
        document.getElementById('json-output-format').value = '';
    }

    clearValidateInput() {
        document.getElementById('json-input-validate').value = '';
        document.getElementById('validation-result').innerHTML = '';
    }

    clearConvertInput() {
        document.getElementById('json-input-convert').value = '';
        document.getElementById('json-output-convert').value = '';
    }

    // 复制到剪贴板
    copyToClipboard(elementId) {
        const element = document.getElementById(elementId);
        if (!element || !element.value) {
            this.showToast('没有内容可复制', 'warning');
            return;
        }

        element.select();
        element.setSelectionRange(0, 99999); // 移动端兼容

        try {
            document.execCommand('copy');
            this.showToast('已复制到剪贴板', 'success');
        } catch (err) {
            this.showToast('复制失败，请手动选择复制', 'error');
        }
    }

    // 下载JSON文件
    downloadJSON(elementId) {
        const element = document.getElementById(elementId);
        if (!element || !element.value) {
            this.showToast('没有内容可下载', 'warning');
            return;
        }

        const content = element.value;
        const blob = new Blob([content], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = `json-data-${new Date().getTime()}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        this.showToast('文件下载成功', 'success');
    }

    // 显示提示消息
    showToast(message, type = 'info') {
        // 创建toast元素
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.style.position = 'fixed';
        toast.style.top = '20px';
        toast.style.right = '20px';
        toast.style.padding = '12px 20px';
        toast.style.borderRadius = '4px';
        toast.style.color = 'white';
        toast.style.zIndex = '10000';
        toast.style.fontSize = '14px';
        toast.style.minWidth = '200px';
        toast.style.textAlign = 'center';
        toast.style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)';
        
        // 设置背景颜色基于类型
        const colors = {
            success: '#4caf50',
            warning: '#ff9800',
            error: '#f44336',
            info: '#2196f3'
        };
        toast.style.backgroundColor = colors[type] || colors.info;
        
        toast.textContent = message;
        
        // 添加到页面
        document.body.appendChild(toast);
        
        // 3秒后自动消失
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 3000);
    }
}

// 全局函数，供HTML调用
function switchJSONTab(tabName) {
    console.log('切换到标签页:', tabName);
    
    // 移除所有标签页的active类
    const tabs = document.querySelectorAll('#json-tool .input-tab');
    tabs.forEach(tab => {
        tab.classList.remove('active');
    });
    
    // 为当前标签页添加active类
    const currentTab = document.querySelector(`#json-tool [data-tab="${tabName}"]`);
    if (currentTab) {
        currentTab.classList.add('active');
    }
    
    // 隐藏所有内容区域
    const contents = document.querySelectorAll('#json-tool .input-content');
    contents.forEach(content => {
        content.classList.remove('active');
    });
    
    // 显示当前内容区域
    const currentContent = document.getElementById(`${tabName}-input`);
    if (currentContent) {
        currentContent.classList.add('active');
    }
    
    console.log('标签页切换完成');
}

function formatJSON() {
    if (!window.jsonTool) {
        window.jsonTool = new JSONTool();
    }
    window.jsonTool.formatJSON();
}

function compressJSON() {
    if (!window.jsonTool) {
        window.jsonTool = new JSONTool();
    }
    window.jsonTool.compressJSON();
}

function unicodeToChinese() {
    if (!window.jsonTool) {
        window.jsonTool = new JSONTool();
    }
    window.jsonTool.unicodeToChinese();
}

function compressJSON() {
    if (!window.jsonTool) {
        window.jsonTool = new JSONTool();
    }
    window.jsonTool.compressJSON();
}

function validateJSON() {
    if (!window.jsonTool) {
        window.jsonTool = new JSONTool();
    }
    window.jsonTool.validateJSON();
}

function convertJSON() {
    if (!window.jsonTool) {
        window.jsonTool = new JSONTool();
    }
    window.jsonTool.convertJSON();
}

function clearJSONInput() {
    if (!window.jsonTool) {
        window.jsonTool = new JSONTool();
    }
    window.jsonTool.clearJSONInput();
}

function clearValidateInput() {
    if (!window.jsonTool) {
        window.jsonTool = new JSONTool();
    }
    window.jsonTool.clearValidateInput();
}

function clearConvertInput() {
    if (!window.jsonTool) {
        window.jsonTool = new JSONTool();
    }
    window.jsonTool.clearConvertInput();
}

function copyToClipboard(elementId) {
    if (!window.jsonTool) {
        window.jsonTool = new JSONTool();
    }
    window.jsonTool.copyToClipboard(elementId);
}

function downloadJSON(elementId) {
    if (!window.jsonTool) {
        window.jsonTool = new JSONTool();
    }
    window.jsonTool.downloadJSON(elementId);
}